<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blogs/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blogs/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blogs/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blogs/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/blogs/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/blogs/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/blogs/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="Node.js," />










<meta name="description" content="文件上传与下载1.NodeJS遍历某文件夹下的所有文件nodejs提供了一个方法用于遍历文件夹下的所有文件，返回一个数组 12345678910111213function getfiles(path)&amp;#123;    &#x2F;&#x2F;读取目录下所有目录文件  返回数组    return fs.readdirSync(path,&amp;#123;encoding:&amp;#x27;utf8&amp;#x27;, withFi">
<meta property="og:type" content="article">
<meta property="og:title" content="NodeJS文件上传与下载">
<meta property="og:url" content="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/index.html">
<meta property="og:site_name" content="Chao&#39;s blog">
<meta property="og:description" content="文件上传与下载1.NodeJS遍历某文件夹下的所有文件nodejs提供了一个方法用于遍历文件夹下的所有文件，返回一个数组 12345678910111213function getfiles(path)&amp;#123;    &#x2F;&#x2F;读取目录下所有目录文件  返回数组    return fs.readdirSync(path,&amp;#123;encoding:&amp;#x27;utf8&amp;#x27;, withFi">
<meta property="og:locale">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/2.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/1.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/3.png">
<meta property="og:image" content="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/4.png">
<meta property="article:published_time" content="2022-06-20T11:51:01.000Z">
<meta property="article:modified_time" content="2022-06-22T14:54:26.854Z">
<meta property="article:author" content="Chaoyxy">
<meta property="article:tag" content="Node.js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/2.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Gemini',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS文件上传与下载/"/>





  <title>NodeJS文件上传与下载 | Chao's blog</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blogs/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chao's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blogs/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blogs/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blogs/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://louchaoyy.gitee.io/blogs/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blogs/images/cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chao's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">NodeJS文件上传与下载</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-06-20T19:51:01+08:00">
                2022-06-20
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count disqus-comment-count"
                        data-disqus-identifier="2022/06/20/NodeJS文件上传与下载/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="文件上传与下载"><a href="#文件上传与下载" class="headerlink" title="文件上传与下载"></a>文件上传与下载</h1><h2 id="1-NodeJS遍历某文件夹下的所有文件"><a href="#1-NodeJS遍历某文件夹下的所有文件" class="headerlink" title="1.NodeJS遍历某文件夹下的所有文件"></a>1.NodeJS遍历某文件夹下的所有文件</h2><p>nodejs提供了一个方法用于遍历文件夹下的所有文件，返回一个数组</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getfiles</span>(<span class="params">path</span>)</span>&#123;    <span class="comment">//读取目录下所有目录文件  返回数组</span></span><br><span class="line">    <span class="keyword">return</span> fs.readdirSync(path,&#123;<span class="attr">encoding</span>:<span class="string">&#x27;utf8&#x27;</span>, <span class="attr">withFileTypes</span>:<span class="literal">true</span>&#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isFile</span>(<span class="params">filepath</span>)</span>&#123;  <span class="comment">//判断是否是文件 Boolean</span></span><br><span class="line">    <span class="keyword">let</span> stat = fs.statSync(filepath)</span><br><span class="line">    <span class="keyword">return</span> stat.isFile()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isDir</span>(<span class="params">filepath</span>)</span>&#123;  <span class="comment">//判断是否是文件夹 Boolean</span></span><br><span class="line">    <span class="keyword">let</span> stat = fs.statSync(filepath)</span><br><span class="line">    <span class="keyword">return</span> stat.isDirectory()</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<p>递归遍历所有文件夹和文件</p>
<span id="more"></span>

<p>param1:路径  param2:将结果存储到该数组中</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//递归遍历所有文件夹和文件</span></span><br><span class="line"><span class="comment">// param1:路径  param2:将结果存储到该数组中</span></span><br><span class="line"><span class="keyword">let</span> time = <span class="number">0</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getAllfiles</span>(<span class="params">path, arr</span>)</span>&#123; 	<span class="comment">// 结果将存储到arr数组中</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&#x27;该函数已递归&#x27;</span>, ++time, <span class="string">&#x27;次&#x27;</span>)</span><br><span class="line">    <span class="keyword">let</span> filesArr = getfiles(path);     <span class="comment">// 获取目录下所有文件</span></span><br><span class="line">    filesArr.forEach(<span class="function"><span class="params">item</span>=&gt;</span>&#123;</span><br><span class="line">    	<span class="comment">// 需要过滤掉的文件  item是文件名或文件夹名</span></span><br><span class="line">        <span class="keyword">if</span> (</span><br><span class="line">            item == <span class="string">&#x27;$RECYCLE.BIN&#x27;</span> || </span><br><span class="line">            item.includes(<span class="string">&#x27;asar&#x27;</span>) || </span><br><span class="line">            item == <span class="string">&#x27;System Volume Information&#x27;</span> ||  </span><br><span class="line">            item == <span class="string">&#x27;is&#x27;</span> || </span><br><span class="line">            item == <span class="string">&#x27;http-timer&#x27;</span> || </span><br><span class="line">            item == <span class="string">&#x27;abbrev&#x27;</span> || </span><br><span class="line">            item == <span class="string">&#x27;node_modules&#x27;</span> || </span><br><span class="line">            item == <span class="string">&#x27;study&#x27;</span></span><br><span class="line">            ) &#123;</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span>(isDir(path + item))&#123; <span class="comment">//如果是文件夹</span></span><br><span class="line">            <span class="keyword">let</span> itemFileArr = []</span><br><span class="line">            getAllfiles(path + item + <span class="string">&#x27;/&#x27;</span>, itemFileArr)</span><br><span class="line">            <span class="keyword">let</span> dir = &#123;<span class="attr">name</span>:item, <span class="attr">type</span>:<span class="string">&#x27;dir&#x27;</span>, <span class="attr">item</span>:itemFileArr&#125;</span><br><span class="line">            arr.push(dir)</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(isFile(path + item))&#123;  <span class="comment">// 如果是文件</span></span><br><span class="line">            arr.push(&#123;<span class="attr">name</span>:item, <span class="attr">type</span>:<span class="string">&#x27;file&#x27;</span>&#125;)</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">return</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="2-文件上传"><a href="#2-文件上传" class="headerlink" title="2.文件上传"></a>2.文件上传</h2><p>路由</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> uploadFile = <span class="built_in">require</span>(<span class="string">&#x27;../files/uploadFile&#x27;</span>);</span><br><span class="line"></span><br><span class="line">router.post(<span class="string">&#x27;/upload&#x27;</span>,uploadFile.upload.single(<span class="string">&#x27;file&#x27;</span>),apiHandler.uploadFile);</span><br></pre></td></tr></table></figure>

<p>文件上传，使用了multer中间件</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@name</span>:uploadFile</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span>:louchao</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span>:2022/5/31 21:04</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> multer = <span class="built_in">require</span>(<span class="string">&#x27;multer&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> Storage = multer.diskStorage(&#123;</span><br><span class="line">    <span class="attr">destination</span>:<span class="function"><span class="keyword">function</span> (<span class="params">req,file,cb</span>) </span>&#123;</span><br><span class="line">        <span class="comment">//指定路径</span></span><br><span class="line">        cb(<span class="literal">null</span>,<span class="string">&#x27;uploadFiles&#x27;</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="attr">filename</span>:<span class="function"><span class="keyword">function</span> (<span class="params">req,file,cb</span>) </span>&#123;</span><br><span class="line">        <span class="comment">//指定文件名</span></span><br><span class="line">        cb(<span class="literal">null</span>,<span class="built_in">Date</span>.now()+<span class="string">&quot;_&quot;</span>+file.originalname);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> upload = multer(&#123;<span class="attr">storage</span>:Storage&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.upload = upload;</span><br></pre></td></tr></table></figure>

<p>路由处理函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">exports</span>.uploadFile = <span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        res.send(<span class="built_in">JSON</span>.stringify(req.file));</span><br><span class="line">        <span class="built_in">console</span>.log(req.file);</span><br><span class="line">    &#125;<span class="keyword">catch</span> (e) &#123;</span><br><span class="line">        res.cc(e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="3-文件下载"><a href="#3-文件下载" class="headerlink" title="3.文件下载"></a>3.文件下载</h2><p>首先根据上传的文件名去查找该目录下是否存在该文件，如果存在就执行下载，如果不存在就返回不存在的响应</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//根据遍历的结果把文件名存入数组</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getFilename</span>(<span class="params">path</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">let</span> fileArr = [];</span><br><span class="line">    <span class="built_in">console</span>.log(getfiles(path));</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span> ; i&lt;getfiles(path).length;i++) &#123;</span><br><span class="line">        <span class="comment">// console.log(getfiles(path)[i].name);</span></span><br><span class="line">        fileArr.push(getfiles(path)[i].name);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * for in循环</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="comment">// for (const pathKey in getfiles(path)) &#123;</span></span><br><span class="line">    <span class="comment">//     console.log(getfiles(path)[pathKey].name);</span></span><br><span class="line">    <span class="comment">//     fileArr.push(getfiles(path)[pathKey].name)</span></span><br><span class="line">    <span class="comment">// &#125;</span></span><br><span class="line">    <span class="keyword">return</span> fileArr;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//目录下是否存在目标文件</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">fileIndir</span>(<span class="params">fileName,fileNames</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">const</span> key <span class="keyword">in</span> fileNames) &#123;</span><br><span class="line">        <span class="keyword">if</span> (fileName === fileNames[key])</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>res响应</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//文件下载</span></span><br><span class="line"><span class="built_in">exports</span>.download = <span class="function">(<span class="params">req,res</span>)=&gt;</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(req.body);</span><br><span class="line">    res.send(&#123;</span><br><span class="line">        <span class="attr">code</span>:<span class="number">200</span>,</span><br><span class="line">        <span class="attr">msg</span>:res.msg,</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>postman测试：</p>
<img src="/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/2.png" class title="不存在文件">

<p>可以下载的情况</p>
<img src="/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/1.png" class title="可以下载">

<h3 id="前端下载"><a href="#前端下载" class="headerlink" title="前端下载"></a>前端下载</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="meta-keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 引入axios.js --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">button</span> <span class="attr">onclick</span>=<span class="string">&quot;downloadFile()&quot;</span>&gt;</span>下载<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="javascript"></span></span><br><span class="line"><span class="javascript">    <span class="function"><span class="keyword">function</span> <span class="title">downloadFile</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">        axios(&#123;</span></span><br><span class="line"><span class="javascript">            <span class="attr">url</span>:<span class="string">&#x27;http://localhost:8888/api/getFile?filename=hello.txt&#x27;</span>,</span></span><br><span class="line"><span class="javascript">            <span class="attr">method</span>: <span class="string">&#x27;get&#x27;</span>,</span></span><br><span class="line"><span class="javascript">            <span class="attr">responseType</span>: <span class="string">&#x27;blob&#x27;</span>,</span></span><br><span class="line"><span class="javascript">            <span class="attr">headers</span>:&#123;</span></span><br><span class="line"><span class="javascript">                <span class="string">&#x27;Authorization&#x27;</span>:<span class="string">&quot;Bearer &quot;</span> +</span></span><br><span class="line"><span class="javascript">                    <span class="string">&quot;eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.&quot;</span> +</span></span><br><span class="line"><span class="javascript">                    <span class="string">&quot;eyJpZCI6MiwidXNlcm5hbWUiOiJsb3VjaGFvIiwicGFzc3dvcmQiOiIiLCJ&quot;</span> +</span></span><br><span class="line"><span class="javascript">                    <span class="string">&quot;pc2RlbGV0ZWQiOjAsImlhdCI6MTY1NTkwNzQyMywiZXhwIjoxNjU1OTExMDIzfQ.&quot;</span> +</span></span><br><span class="line"><span class="javascript">                    <span class="string">&quot;fQigVgOWboWWYsSYG8sIR75pomlyOzpcns058P-fDr8&quot;</span></span></span><br><span class="line"><span class="javascript">            &#125;,</span></span><br><span class="line"><span class="javascript">        &#125;).then(<span class="function"><span class="keyword">function</span> (<span class="params">response</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="comment">// 将响应回来的数据下载为文件，固定代码</span></span></span><br><span class="line"><span class="javascript">            <span class="comment">// 将响应数据处理为Blob类型</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> blob = <span class="keyword">new</span> Blob([response.data]);</span></span><br><span class="line"><span class="javascript">            <span class="comment">// 创建一个URL对象</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> url = <span class="built_in">window</span>.URL.createObjectURL(blob);</span></span><br><span class="line"><span class="javascript">            <span class="comment">// 创建一个a标签</span></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> a = <span class="built_in">document</span>.createElement(<span class="string">&quot;a&quot;</span>);</span></span><br><span class="line"><span class="javascript">            a.href = url;</span></span><br><span class="line"><span class="javascript">            a.download = <span class="string">&quot;hello.txt&quot;</span>;<span class="comment">// 这里指定下载文件的文件名</span></span></span><br><span class="line"><span class="javascript">            a.click();</span></span><br><span class="line"><span class="javascript">            <span class="comment">// 释放之前创建的URL对象</span></span></span><br><span class="line"><span class="javascript">            <span class="built_in">window</span>.URL.revokeObjectURL(url);</span></span><br><span class="line"><span class="javascript">        &#125;).catch(<span class="function"><span class="keyword">function</span> (<span class="params">reason</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="built_in">console</span>.log(reason)</span></span><br><span class="line"><span class="javascript">        &#125;)</span></span><br><span class="line"><span class="javascript">    &#125;</span></span><br><span class="line"><span class="javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>下载结果：</p>
<img src="/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/3.png" class title="下载内容">

<p>原文件</p>
<img src="/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/4.png" class title="原文件内容">

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/alipay.jpg" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="http://chaoyxy.cn/data/User/admin/home/desktop/images/wechatpay.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blogs/tags/Node-js/" rel="tag"># Node.js</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blogs/2022/06/14/vite-vue3%E6%9E%84%E5%BB%BA%E9%A1%B9%E7%9B%AE/" rel="next" title="vite+vue3构建项目">
                <i class="fa fa-chevron-left"></i> vite+vue3构建项目
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blogs/2022/06/23/Websocket%E5%89%8D%E5%90%8E%E7%AB%AF%E9%80%9A%E4%BF%A1/" rel="prev" title="Websocket前后端通信">
                Websocket前后端通信 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a target="_blank" rel="noopener" href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blogs/images/cat.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blogs/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blogs/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/louchaoyy" target="_blank" title="Gitee">
                      
                        <i class="fa fa-fw fa-gitee"></i>Gitee</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="louchao@louchaoyy.cn" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD"><span class="nav-number">1.</span> <span class="nav-text">文件上传与下载</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-NodeJS%E9%81%8D%E5%8E%86%E6%9F%90%E6%96%87%E4%BB%B6%E5%A4%B9%E4%B8%8B%E7%9A%84%E6%89%80%E6%9C%89%E6%96%87%E4%BB%B6"><span class="nav-number">1.1.</span> <span class="nav-text">1.NodeJS遍历某文件夹下的所有文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="nav-number">1.2.</span> <span class="nav-text">2.文件上传</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E6%96%87%E4%BB%B6%E4%B8%8B%E8%BD%BD"><span class="nav-number">1.3.</span> <span class="nav-text">3.文件下载</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%89%8D%E7%AB%AF%E4%B8%8B%E8%BD%BD"><span class="nav-number">1.3.1.</span> <span class="nav-text">前端下载</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chaoyxy</span>

  
</div>

<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.3</div>
-->




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blogs/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blogs/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blogs/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/motion.js?v=5.1.3"></script>



  
  


  <script type="text/javascript" src="/blogs/js/src/affix.js?v=5.1.3"></script>

  <script type="text/javascript" src="/blogs/js/src/schemes/pisces.js?v=5.1.3"></script>



  
  <script type="text/javascript" src="/blogs/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/blogs/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/blogs/js/src/bootstrap.js?v=5.1.3"></script>



  


  

    
      <script id="dsq-count-scr" src="https://Chaoyxy.disqus.com/count.js" async></script>
    

    
      <script type="text/javascript">
        var disqus_config = function () {
          this.page.url = 'https://louchaoyy.gitee.io/blogs/2022/06/20/NodeJS%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E4%B8%8E%E4%B8%8B%E8%BD%BD/';
          this.page.identifier = '2022/06/20/NodeJS文件上传与下载/';
          this.page.title = 'NodeJS文件上传与下载';
        };
        var d = document, s = d.createElement('script');
        s.src = 'https://Chaoyxy.disqus.com/embed.js';
        s.setAttribute('data-timestamp', '' + +new Date());
        (d.head || d.body).appendChild(s);
      </script>
    

  




	





  














  





  

  

  

  
  

  

  

  

</body>
</html>
